(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.amendment.updateController", updateController);
	updateController.$inject = [ "$q", "$scope", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "arithService", "amendmentService" ];
	function updateController($q, $scope, modalService, gridService, layoutConfig, validatorConfig, authService, arithService, amendmentService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.amendment = {};
		ctrl.amendment.pastdueSchdNewList = [];

		ctrl.init = function() {
			amendmentService.initDataOptions().then(function(initData) {
				return $q(function(resolved, rejected) {
					ctrl.countryOptions = initData.country;
					ctrl.spreadTierTypeOptions = initData.spreadTierType;
					resolved();
				});
			}).then(function() {
				authService.updateInit(params).then(function(response) {
					ctrl.amendment = response.data.model;
					ctrl.amendment.taskId = response.data.task.taskId;
					ctrl.princAmtChgChanged(ctrl.amendment);
					resetTabs();
					amendmentService.resetHasFrontSameCriteria(ctrl.amendment.intSchdNewList, "Y", "Y");
					amendmentService.resetHasFrontSameCriteria(ctrl.amendment.intSchdOldList, "Y", "Y");

					amendmentService.processPastDue(ctrl.amendment, ctrl.intSchdNewListGridOptions);// if loan is past due, then
					// set read only
					amendmentService.setpastDueSchdDate(ctrl.amendment);// set date into pastdueSchd for

					// loan interest is prepaid, interest radio is No and
					// readonly
					if (ctrl.amendment.loan.loanInt.intCollMethod == "P") {
						ctrl.amendment.interestFlag = "N";
					}
					amendmentService.resetPastdueSchdList(ctrl.amendment);
					// pastdueReadonlyFlag
					if (ctrl.amendment.loan.loanInfo.loanStatus == "P" && (!ctrl.amendment.pastdueSchdNewList || ctrl.amendment.pastdueSchdNewList.length == 0)) {
						ctrl.pastdueReadonlyFlag = "Y";
					} else {
						ctrl.pastdueReadonlyFlag = "N";
					}
					// reset interest schd
					amendmentService.resetIntSchdList(ctrl.amendment, ctrl.intSchdNewListGridOptions, ctrl.intSchdOldListGridOptions);
				});
			});

			/** ***************Past Due****************** */
			if (ctrl.validatorConfig)
				ctrl.layoutConfig.formConfigs.pastdueNew.tableConfigs.table.validatorConfig = ctrl.validatorConfig.pastdueSchdNewList;
			ctrl.pastdueSchdNewListGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.pastdueNew.tableConfigs.table, function (eventRow, selectedRows) {
				ctrl.selectedPastdues = selectedRows;
			});
			ctrl.pastdueSchdNewListGridOptions.data = "vm.amendment.pastdueSchdNewList";
			ctrl.pastdueSchdNewListGridOptions.enableOperation = true;
			ctrl.pastdueSchdNewListGridOptions.enableOperationRemoveSelected = true;

			ctrl.pastdueSchdNewListGridOptions.addRow = function(row) {
				return $q(function(resolved, rejected) {
					var pastdueTenorFrom;
					if (ctrl.amendment.pastdueSchdNewList && ctrl.amendment.pastdueSchdNewList.length > 0) {
						var prePastdueTenor = ctrl.amendment.pastdueSchdNewList[ctrl.amendment.pastdueSchdNewList.length - 1].pastdueTenor;
						if (!prePastdueTenor) {
							modalService.openErrorDialogs({
								messages : [ "The To n-th Day must be not null!" ]
							});
							rejected();
							return;
						}
						pastdueTenorFrom = arithService.add(prePastdueTenor, 1);
					} else {
						pastdueTenorFrom = 1;
					}
					row.pastdueTenorFrom = pastdueTenorFrom;
					resolved();
				});
			};

			ctrl.pastdueSchdNewListGridOptions.filterRowOperation = function(row, type) {
				if (row && row.entity && (row.entity.readonlyFlag) && (type == "remove")) {
					return true;
				} else {
					return false;
				}
			};

			ctrl.pastdueSchdOldListGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.pastdueOld.tableConfigs.table, null);
			ctrl.pastdueSchdOldListGridOptions.data = "vm.amendment.pastdueSchdOldList";
			ctrl.pastdueSchdOldListGridOptions.enableOperation = false;
			ctrl.pastdueSchdOldListGridOptions.enableRowHeaderSelection = false;
			/** ***************Past Due****************** */

			/** ***************interest****************** */
			ctrl.intSchdNewListGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.intSchdNew.tableConfigs.table, null);
			ctrl.intSchdNewListGridOptions.data = "vm.amendment.intSchdNewList";

			ctrl.intSchdNewListGridOptions.filterRowOperation = function(row, type) {
				if ((!ctrl.amendment.loan.loanInt.spreadTierType2 || ctrl.amendment.loan.loanInt.spreadTierType2 == "N")
						&& (!ctrl.amendment.loan.loanInt.spreadTierType || ctrl.amendment.loan.loanInt.spreadTierType == "N")) {
					return true;
				} else if (row && row.entity && (row.entity.hasFrontSameCriteria == "Y" || row.entity.pastDueFlag) && (type == "add")) {
					return true;
				} else if (row && row.entity && (row.entity.pastDueFlag) && (type == "remove")) {
					return true;
				} else {
					return false;
				}
			};

			ctrl.intSchdOldListGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.intSchdOld.tableConfigs.table, null);
			ctrl.intSchdOldListGridOptions.data = "vm.amendment.intSchdOldList";
			
			ctrl.initTabs();
		};
		/** ***************interest****************** */
		ctrl.baseRateNewChanged = function(amendment) {
			amendmentService.baseRateNewChanged(amendment);
		};
		ctrl.totalSpreadRateNewChanged = function(amendment) {
			amendmentService.totalSpreadRateNewChanged(amendment);
		};
		ctrl.spreadRateNewChanged = function(amendment) {
			amendmentService.spreadRateNewChanged(amendment);
		};

		ctrl.baseRateOldChanged = function(amendment) {
			amendmentService.baseRateOldChanged(amendment);
		};
		ctrl.totalSpreadRateOldChanged = function(amendment) {
			amendmentService.totalSpreadRateOldChanged(amendment);
		};
		ctrl.spreadRateOldChanged = function(amendment) {
			amendmentService.spreadRateOldChanged(amendment);
		};

		ctrl.princAmtChgChanged = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.princAmtChgChanged(amendment);
		};

		ctrl.obligorCodeNew = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.obligorCodeNew(amendment);
		};

		ctrl.save = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else if (!amendmentService.resetUFlag(ctrl.amendment)) {
				modalService.openErrorDialogs({
					"messages" : [ "title.dialogs.info.loanamd.nochanged" ]
				});
			} else {
				// must after resetUFlag
				amendmentService.validateBilling(ctrl.amendment, messages);
				if (messages.length > 0) {
					modalService.openErrorDialogs({
						"messages" : messages
					});
				}
				return authService.updateSaved(ctrl.amendment).then(submitSuccessful, submitFailed);
			}
		};

		ctrl.settlement = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else if (!amendmentService.resetUFlag(ctrl.amendment)) {
				modalService.openErrorDialogs({
					"messages" : [ "title.dialogs.info.loanamd.nochanged" ]
				});
			} else {
				return authService.updateSubmitted(ctrl.amendment).then(submitSuccessful, submitFailed);
			}
		};

		ctrl.cancel = function() {
			modalService.openConfirmDialogs({
				"messages" : [ {
					msg : "title.dialog.confirm.cancel",
					args : [ ctrl.amendment.primaryKey ]
				} ],
				"btnCallback" : {
					"ok" : function() {
						authService.updateCancelled(ctrl.amendment).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.cancel" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

		/** *****************pastdue********************* */

		ctrl.removePastdue = function(row) {
			angular.forEach(ctrl.selectedPastdues, function(selectedPastdue, key) {
				angular.forEach(ctrl.amendment.pastdueSchdNewList, function(pastdue, index) {
					if (pastdue.$$hashKey == selectedPastdue.$$hashKey) {
						ctrl.amendment.pastdueSchdNewList.splice(index, 1);
					}
				});
			});

			// reset pastdueTenorFrom
			var pastdueTenorFrom = 1;
			angular.forEach(ctrl.amendment.pastdueSchdNewList, function(pastdue, index) {
				pastdue.pastdueTenorFrom = pastdueTenorFrom;
				pastdueTenorFrom = arithService.add(formatService.parseNumber(pastdue.pastdueTenor), 1);
			});
		};

		ctrl.pastdueTenorChanged = function(rowObj) {
			amendmentService.pastdueTenorChanged(ctrl.amendment.pastdueSchdNewList, rowObj);
		};

		ctrl.pastdueGraceChanged = function(rowObj) {
			amendmentService.pastdueGraceChanged(ctrl.amendment.pastdueSchdNewList, rowObj);
		};

		ctrl.pastdueTenorOldChanged = function(rowObj) {
			amendmentService.pastdueTenorChanged(ctrl.amendment.pastdueSchdOldList, rowObj);
		};

		ctrl.pastdueGraceOldChanged = function(rowObj) {
			amendmentService.pastdueGraceChanged(ctrl.amendment.pastdueSchdOldList, rowObj);
		};
		/** *****************pastdue********************* */

		/** *****************interest********************* */
		ctrl.addIntSchd = function(row) {
			row.hasFrontSameCriteria = "N";
		};

		ctrl.removeIntSchdRow = function(row) {
			amendmentService.resetSpreadTierShow(row.entity, ctrl.amendment.intSchdNewList);
		};

		ctrl.addSubRow = function(row) {
			var _selectedTierCriteria;
			var _selectedTierCriteriaIndex;
			var selectedNum = 0;
			angular.forEach(ctrl.amendment.intSchdNewList, function(spreadTier, index) {
				if (spreadTier.$$hashKey == row.entity.$$hashKey) {
					_selectedTierCriteria = spreadTier;
					_selectedTierCriteriaIndex = index;
					selectedNum = selectedNum + 1;
				}
			});

			var newTierCriteria = {};
			newTierCriteria.hasFrontSameCriteria = "Y";
			newTierCriteria.criteria = _selectedTierCriteria.criteria;
			ctrl.amendment.intSchdNewList.splice(_selectedTierCriteriaIndex + 1, 0, newTierCriteria);
		};

		/** *****************interest********************* */

		ctrl.initTabs = function() {
			// if flag (generalFlag,obligorFlag,interestFlag,pastdueFlag,billingScheduleFlag) is N,then set New = Old
			amendmentService.resetNewOld(ctrl.amendment);
			ctrl.tabsetIndex = amendmentService.initTabs(ctrl.amendment);
		};

		function resetTabs() {
			if (ctrl.amendment.uMaturityDate == "Y" || ctrl.amendment.uCustRef == "Y" || ctrl.amendment.uPrincAmt == "Y" || ctrl.amendment.uAssetAmt == "Y" || ctrl.amendment.uPerform == "Y"
					|| ctrl.amendment.uRepeatExtendFlag == "Y" || ctrl.amendment.uRepeatExtendTenor == "Y" || ctrl.amendment.amdComments) {
				ctrl.amendment.generalFlag = "Y";
			}
			if (ctrl.amendment.uObligorInfo == "Y" || ctrl.amendment.uLiabAcctCode == "Y") {
				ctrl.amendment.obligorFlag = "Y";
			}
			if (ctrl.amendment.uBaseRate == "Y" || ctrl.amendment.uSpreadRate == "Y" || ctrl.amendment.uCofRate == "Y" || ctrl.amendment.uInsRate == "Y" || ctrl.amendment.uTaxRate == "Y"
					|| ctrl.amendment.uIntReview == "Y") {
				ctrl.amendment.interestFlag = "Y";
			}
			if (ctrl.amendment.uPastdue == "Y") {
				ctrl.amendment.pastdueFlag = "Y";
			}
			if (ctrl.amendment.uBill == "Y") {
				ctrl.amendment.billingScheduleFlag = "Y";
			}
			ctrl.initTabs();
		}

		/** *****************billing********************* */
		ctrl.billFirstOnNewChanged = function(amendment, form, firstLoad) {
			if(firstLoad){
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};
		ctrl.billOnEomNewChanged = function(amendment, form, firstLoad) {
			if(firstLoad){
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};
		ctrl.billFreqTypeNewChanged = function(amendment, form, firstLoad) {
			if(firstLoad){
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};
		/** *****************billing********************* */
	}
})(angular);
